package io.renren.modules.web.controller;

import io.renren.common.utils.R;
import io.renren.modules.web.entity.WebKnowledgeEntity;
import io.renren.modules.web.service.WebKnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Web开发知识控制器
 */
@RestController
@RequestMapping("/web/knowledge")
public class KnowledgeController {

    @Autowired
    private WebKnowledgeService webKnowledgeService;

    /**
     * 获取所有知识类型
     */
    @GetMapping("/types")
    public R getAllTypes() {
        List<WebKnowledgeEntity> types = webKnowledgeService.getAllTypes();
        return R.ok().put("data", types);
    }

    /**
     * 根据类型获取章节列表
     */
    @GetMapping("/chapters/{type}")
    public R getChaptersByType(@PathVariable("type") Integer type) {
        List<WebKnowledgeEntity> chapters = webKnowledgeService.getChaptersByType(type);
        return R.ok().put("data", chapters);
    }

    /**
     * 根据类型和章节ID获取知识内容
     */
    @GetMapping("/{type}/{chapterId}")
    public R getKnowledge(@PathVariable("type") Integer type, @PathVariable("chapterId") Integer chapterId) {
        WebKnowledgeEntity knowledge = webKnowledgeService.getKnowledgeByTypeAndChapter(type, chapterId);
        if (knowledge != null) {
            return R.ok().put("data", knowledge);
        } else {
            return R.error("未找到相关知识内容");
        }
    }

    /**
     * 添加新知识
     */
    @PostMapping("/add")
    public R addKnowledge(@RequestBody WebKnowledgeEntity knowledge) {
        boolean success = webKnowledgeService.save(knowledge);
        if (success) {
            return R.ok("添加成功");
        } else {
            return R.error("添加失败");
        }
    }

    /**
     * 更新知识
     */
    @PutMapping("/update")
    public R updateKnowledge(@RequestBody WebKnowledgeEntity knowledge) {
        boolean success = webKnowledgeService.updateById(knowledge);
        if (success) {
            return R.ok("更新成功");
        } else {
            return R.error("更新失败");
        }
    }

    /**
     * 删除知识
     */
    @DeleteMapping("/{id}")
    public R deleteKnowledge(@PathVariable("id") Integer id) {
        boolean success = webKnowledgeService.removeById(id);
        if (success) {
            return R.ok("删除成功");
        } else {
            return R.error("删除失败");
        }
    }
} 